package com.dz.lm.service.moneyBar.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dz.lm.common.dto.MoneyBarDTO;
import com.dz.lm.common.exception.DaoException;
import com.dz.lm.common.exception.ServiceException;
import com.dz.lm.common.util.JPushUtils;
import com.dz.lm.dao.product.read.CommonAreaDao;
import com.dz.lm.dao.reminder.write.ReminderDao;
import com.dz.lm.domain.agent.Agent;
import com.dz.lm.domain.business.ApplyProduct;
import com.dz.lm.domain.moneybar.MoneyBar;
import com.dz.lm.domain.moneybar.AgentNode;
import com.dz.lm.domain.product.CommonArea;
import com.dz.lm.domain.product.Product;
import com.dz.lm.service.AbstractService;
import com.dz.lm.service.BeanRefUtil;
import com.dz.lm.service.moneyBar.MoneyBarService;
import  com.dz.lm.common.dto.ApplyProductDTO;
import com.google.common.collect.Maps;

@Service
public class MoneyBarServiceImpl extends AbstractService implements MoneyBarService{
	
	@Resource(name="readMoneyBarDao")
	private com.dz.lm.dao.moneyBar.read.MoneyBarDao readMoneyBarDao;
	
	@Resource(name="writeMoneyBarDao")
	private com.dz.lm.dao.moneyBar.write.MoneyBarDao writeMoneyBarDao;
	
	@Resource(name="writeAgentDao")
	private com.dz.lm.dao.agent.write.AgentDao writeAgentDao;
	
	@Resource(name="writeProductDao")
	private com.dz.lm.dao.product.write.ProductDao writeProductDao;
	
	@Resource(name="readProductDao")
	private com.dz.lm.dao.product.read.ProductDao readProductDao;
	
	@Resource(name="readAgentProductDao")
	private com.dz.lm.dao.product.read.AgentProductDao readAgentProductDao;
	
	@Resource(name = "readCommonAreaDao")
	private CommonAreaDao readCommonAreaDao;
	
	@Resource(name = "writeReminderDao")
	private ReminderDao writeReminderDao;
	
	@Resource(name="readLoginLogDao")
	private com.dz.lm.dao.log.read.LoginLogDao loginLogDao;
	
	@Resource(name="readUserDao")
	private com.dz.lm.dao.user.read.UserDao userDao;
	
	public Logger logger = LogManager.getLogger(getClass());

	@Override
	public List<Map<String, Object>> qryLocalList() throws ServiceException {
		List<Map<String, Object>> retList = new ArrayList<Map<String, Object>>();
    	Map<String, Object> sub = new HashMap<String, Object>();
    	Map<String, Object> city = new HashMap<String, Object>();
    	List<Map<String, Object>> cities = new ArrayList<Map<String, Object>>();
    	try {
    		List<Map<String, Object>> localList = readCommonAreaDao.qryLocalList();
    		Object pId = null;
    		for (Map<String, Object> p : localList) {
    			if (pId == null) {
    				pId = p.get("pId");
    			}
    			if (!pId.equals(p.get("pId"))) {
    				pId = p.get("pId");
    				sub.put("cityList", cities);
    				retList.add(sub);
    				sub = new HashMap<String, Object>();
    				cities = new ArrayList<Map<String, Object>>();
    			}
    			sub.put("pId", p.get("pId"));
    			sub.put("name", p.get("pName"));
    			city.put("cId", p.get("cId"));
    			city.put("name", p.get("name"));
    			cities.add(city);
    			city = new HashMap<String, Object>();
    		}
		} catch (DaoException e) {
			new ServiceException(e.getCause());
		}
    	return retList;
	}

	public Map<String, Object> siftingSearch(Map<String, Object> qryParam) throws ServiceException {
		Map<String, Object> retMap = new HashMap<String, Object>();
		List<Map<String, Object>> moneyBarList = null;
		Integer count = 0;
		try {
			// 返回数据明细
			moneyBarList = readMoneyBarDao.searchMoneyBarList(qryParam);
			// 返回数据总条数
			count = readMoneyBarDao.searchMoneyBarListCount(qryParam);
		} catch (DaoException e) {
			throw new ServiceException(e.getCause());
		}
		retMap.put("moneyBarList", moneyBarList);
		retMap.put("count", count);
		return retMap;
	}

	@Override
	public Map<String, Object> homeMoneyBarList(Map<String, Object> qryParam) throws ServiceException {
		Map<String, Object> retMap = new HashMap<String, Object>();
		List<Map<String, Object>> moneyBarList = null;
		Integer count = 0;
		try {
			// 返回数据明细
			moneyBarList = readMoneyBarDao.homeMoneyBarList(qryParam);
			// 返回数据总条数
			count = readMoneyBarDao.homeMoneyBarListCount(qryParam);
		} catch (DaoException e) {
			throw new ServiceException(e.getCause());
		}
		retMap.put("moneyBarList", moneyBarList);
		retMap.put("count", count);
		return retMap;
	}

	@Override
	@Transactional
	public Map<String, Object> qryMoneyBarDetail(Map<String, Object> qryParam) throws ServiceException {
		Map<String, Object> retMap = new HashMap<String, Object>();
//		MoneyBar moneyBar = null;
		List<Product> products = new ArrayList<Product>();
		Integer productCount = 0;
		List<Map<String, Long>> productAgentCount = new ArrayList<Map<String, Long>>();;
		int barAgentCount = 0;
		try {
//			moneyBar = readMoneyBarDao.selectByPrimaryKey(qryParam);
			products = readMoneyBarDao.qryMoneyBarProductList(qryParam);
			productCount = readMoneyBarDao.qryMoneyBarProductListCount(qryParam);
			productAgentCount = readMoneyBarDao.qryMoneyBarProductAgentCount(qryParam);
			barAgentCount = readMoneyBarDao.qryMoneyBarProductAgentTotalCnt(qryParam);
		} catch (DaoException e) {
			throw new ServiceException(e.getCause());
		}
//		retMap.put("moneyBar", moneyBar);
		retMap.put("productList", products);
		retMap.put("productCount", productCount);
		retMap.put("productAgentCount", productAgentCount);
		retMap.put("barAgentCount", barAgentCount);
		return retMap;
	}
	
	
	
	@Override
	public int addMoneyBar(Map<String, Object> param) throws ServiceException {
		try {
			if (param.get("promoCode") != null && !"".equals(param.get("promoCode"))) {
				Map<String, Object> promocode = userDao.qryUserPromoCode(param);
				if (promocode == null || promocode.isEmpty()) {
					return -1;
				}
			}
			return writeMoneyBarDao.insert(param);
		} catch (DaoException e) {
			throw new ServiceException(e.getCause());
		}
	}

	@Override
	public int deleteMoneyBar(Map<String, Object> param) throws ServiceException {
		return 0;
	}
	
    public int modifyMoneyBar(Map<String, Object> param) throws ServiceException{
    	try {
			return writeMoneyBarDao.update(param);
		} catch (DaoException e) {
			throw new ServiceException(e.getCause());
		}
    }

	@Override
	public MoneyBarDTO getMoneyBarById(Map<String, Object> qryParam) throws ServiceException {
		MoneyBarDTO moneyBarDto = new MoneyBarDTO();
		try {
			MoneyBar moneyBar = readMoneyBarDao.selectByPrimaryKey(qryParam);
			CommonArea province = readCommonAreaDao.selectByPrimaryKey(Integer.parseInt(moneyBar.getProvince()));
			CommonArea city = new CommonArea();
			if (moneyBar.getCity() != null) {
				city = readCommonAreaDao.selectByPrimaryKey(Integer.parseInt(moneyBar.getCity()));
			}
			Map<String, String> fieldValue = BeanRefUtil.getFieldValueMap(moneyBar);
			BeanRefUtil.setFieldValue(moneyBarDto,fieldValue);
			moneyBarDto.setLocation(province.getName() + (city.getName() != null ? "-" + city.getName() : ""));
		} catch (DaoException e) {
			throw new ServiceException(e.getCause());
		}
		return  moneyBarDto;
	}

	@Override
	public List<MoneyBarDTO> qryMoneyBarListByUserId(Map<String, Object> qryParam) throws ServiceException {
		List<MoneyBarDTO> moneyBarDtoList = new ArrayList<MoneyBarDTO>();
		try {
			List<MoneyBar> moneyBarlist = readMoneyBarDao.qryMoneyBarListByUserId(qryParam);
			for (MoneyBar moneyBar : moneyBarlist) {
				MoneyBarDTO moneyBarDto = new MoneyBarDTO();
				Map<String, String> fieldValue = BeanRefUtil.getFieldValueMap(moneyBar);
				BeanRefUtil.setFieldValue(moneyBarDto, fieldValue);
				moneyBarDtoList.add(moneyBarDto);
			}
		} catch (DaoException e) {
			throw new ServiceException(e.getCause());
		}
		return  moneyBarDtoList;
	}

	@Override
	public Map<String, Object> qryMoneyBarApplyProductList(Map<String, Object> qryParam) throws ServiceException {
		Map<String, Object> retMap = new HashMap<String, Object>();
		List<ApplyProduct> applyProductList = new ArrayList<ApplyProduct>();
		List<ApplyProductDTO> applyProductdtoList = new ArrayList<ApplyProductDTO>();
		Map<String, List<AgentNode>> nodeMap = new HashMap<String, List<AgentNode>>();
		List<Product> products = new ArrayList<Product>();
		List<AgentNode> nodes = new ArrayList<AgentNode>();
		try {
			//查询这个钱吧下创建的产品列表
			products = readMoneyBarDao.qryMoneyBarProductList2(qryParam);
			for (Product p : products) {
				qryParam.put("productId", p.getProductId());
				//查询产品的一级代理 以及一级代理下的二级代理产品列表
				nodes = readMoneyBarDao.qryMoneyBarAgentList(qryParam);
				for (AgentNode node : nodes) {
					if (node.getAgentClass().equals("1")) {
						List<AgentNode> _nodes = new ArrayList<AgentNode>();
						_nodes.add(node);
						nodeMap.put(node.getUserId() + "-" + node.getParentAgentId() + "-" + node.getAgentClass() + "-"
								+ node.getAgentProductId() + "-" + node.getOriginalProductId(), _nodes);
					} else {
						for (Map.Entry<String, List<AgentNode>> entry : nodeMap.entrySet()) {
							String[] splitKey = entry.getKey().split("-");
							if (splitKey[0].equals(String.valueOf(node.getParentAgentId()))
									&& splitKey[splitKey.length - 1]
											.equals(String.valueOf(node.getOriginalProductId()))) {
								List<AgentNode> _nodes = entry.getValue();
								_nodes.add(node);
							}
						}
					}
				}
			}
			Map<AgentNode, Set<AgentNode>> tempMap = new HashMap<AgentNode, Set<AgentNode>>();
			for (Map.Entry<String, List<AgentNode>> entry : nodeMap.entrySet()) {
				Set<AgentNode> nodeSet = new HashSet<AgentNode>();
				for (AgentNode node : entry.getValue()) {
					if (node.getAgentClass().equals("1")) {
						if (!tempMap.containsKey(node)) {
							tempMap.put(node, nodeSet);
						} else {
							nodeSet = tempMap.get(node);
						}
					} else {
						nodeSet.add(node);
					}
				}
			}
			for (Map.Entry<AgentNode, Set<AgentNode>> entry : tempMap.entrySet()) {
				AgentNode _1leveNode = entry.getKey();
				applyProductList = readMoneyBarDao.qryMoneyBarApplyProductList(_1leveNode.getProductId());
				for (ApplyProduct applyProduct : applyProductList) {
					ApplyProductDTO ApplyProductDto = new ApplyProductDTO();
					Map<String, String> fieldValue = BeanRefUtil.getFieldValueMap(applyProduct);
					BeanRefUtil.setFieldValue(ApplyProductDto, fieldValue);
					Agent agent = new Agent();
					agent.setUserId(_1leveNode.getUserId());
					agent.setLoginName(_1leveNode.getLoginName());
					ApplyProductDto.setProduct(applyProduct.getProduct());
					ApplyProductDto.setApplyUser(applyProduct.getApplyUser());
					ApplyProductDto.setAgent(agent);
					applyProductdtoList.add(ApplyProductDto);
				}
				Set<AgentNode> _2leveNodeSet = entry.getValue();
				for (AgentNode _2leveNode : _2leveNodeSet) {
					applyProductList = readMoneyBarDao.qryMoneyBarApplyProductList2(_2leveNode.getProductId());
					for (ApplyProduct applyProduct : applyProductList) {
						ApplyProductDTO ApplyProductDto = new ApplyProductDTO();
						Map<String, String> fieldValue = BeanRefUtil.getFieldValueMap(applyProduct);
						BeanRefUtil.setFieldValue(ApplyProductDto, fieldValue);
						Agent agent = new Agent();
						agent.setUserId(_2leveNode.getUserId());
						agent.setLoginName(_2leveNode.getLoginName());
						ApplyProductDto.setProduct(applyProduct.getProduct());
						ApplyProductDto.setApplyUser(applyProduct.getApplyUser());
						ApplyProductDto.setAgent(agent);
						applyProductdtoList.add(ApplyProductDto);
					}
				}

			}
		} catch (DaoException e) {
			throw new ServiceException(e.getCause());
		}
		retMap.put("applyProductList", applyProductdtoList);
		return retMap;
	}
	
	@Override
	public Map<String, Object> qryMoneyBarAgentList(Map<String, Object> qryParam) throws ServiceException {
		Map<String, Object> retMap = new HashMap<String, Object>();
		List<Product> products = new ArrayList<Product>();
		Map<String, List<AgentNode>> nodeMap = new HashMap<String, List<AgentNode>>();
		List<AgentNode> nodes = new ArrayList<AgentNode>();
		List<AgentNode> retNodeList = new ArrayList<AgentNode>();
		try {
			products = readMoneyBarDao.qryMoneyBarProductList2(qryParam);
			for (Product p : products) {
				qryParam.put("productId", p.getProductId());
				nodes = readMoneyBarDao.qryMoneyBarAgentList(qryParam);
				for (AgentNode node : nodes) {
					if (node.getAgentClass().equals("1")) {
						List<AgentNode> _nodes = new ArrayList<AgentNode>();
						_nodes.add(node);
						nodeMap.put(node.getUserId() + "-" + node.getParentAgentId() + "-" + node.getAgentClass() + "-"
								+ node.getAgentProductId() + "-" + node.getOriginalProductId(), _nodes);
					} else {
						for (Map.Entry<String, List<AgentNode>> entry : nodeMap.entrySet()) {
							String[] splitKey = entry.getKey().split("-");
							if (splitKey[0].equals(String.valueOf(node.getParentAgentId()))
									&& splitKey[splitKey.length - 1]
											.equals(String.valueOf(node.getOriginalProductId()))) {
								List<AgentNode> _nodes = entry.getValue();
								_nodes.add(node);
							}
						}
					}
				}
			}

			Map<AgentNode, Set<AgentNode>> resultMap = new HashMap<AgentNode, Set<AgentNode>>();
			for (Map.Entry<String, List<AgentNode>> entry : nodeMap.entrySet()) {
				Set<AgentNode> nodeSet = new HashSet<AgentNode>();
				for (AgentNode node : entry.getValue()) {
					AgentNode _1leveNode = new AgentNode(node.getUserId(), node.getProfile(), node.getLoginName(),
							node.getOrderCount(), node.getAgentClass(), node.getOrgAuthFlag(), node.getParentAgentId(),
							node.getState(), null, null, null, null, null);
					if (_1leveNode.getAgentClass().equals("1")) {
						if (!resultMap.containsKey(_1leveNode)) {
							resultMap.put(_1leveNode, nodeSet);
						} else {
							nodeSet = resultMap.get(_1leveNode);
						}
					} else {
						nodeSet.add(_1leveNode);
					}
				}
			}
			
			for (Map.Entry<AgentNode, Set<AgentNode>> entry : resultMap.entrySet()) {
				AgentNode node = entry.getKey();
				List<AgentNode> children = new ArrayList<AgentNode>(entry.getValue());
				node.setChildren(children);
				retNodeList.add(node);
			}
		} catch (DaoException e) {
			throw new ServiceException(e.getCause());
		}
		retMap.put("nodeList", retNodeList);
		return retMap;
	}

	@Override
	public Map<String, Object> qryApplyProductList(Map<String, Object> qryParam) throws ServiceException {
		Map<String, Object> retMap = new HashMap<String, Object>();
		List<ApplyProduct> applyProductList = new ArrayList<ApplyProduct>();
		List<ApplyProductDTO> applyProductdtoList = new ArrayList<ApplyProductDTO>();
		Map<String, List<AgentNode>> nodeMap = new HashMap<String, List<AgentNode>>();
		List<AgentNode> nodes = new ArrayList<AgentNode>();
		try {
			nodes = readMoneyBarDao.qryMoneyBarAgentList(qryParam);
			for (AgentNode node : nodes) {
				if (node.getAgentClass().equals("1")) {
					List<AgentNode> _nodes = new ArrayList<AgentNode>();
					_nodes.add(node);
					nodeMap.put(node.getUserId() + "-" + node.getParentAgentId() + "-" + node.getAgentClass() + "-"
							+ node.getAgentProductId() + "-" + node.getOriginalProductId(), _nodes);
				} else {
					for (Map.Entry<String, List<AgentNode>> entry : nodeMap.entrySet()) {
						String[] splitKey = entry.getKey().split("-");
						if (splitKey[0].equals(String.valueOf(node.getParentAgentId()))
								&& splitKey[splitKey.length - 1].equals(String.valueOf(node.getOriginalProductId()))) {
							List<AgentNode> _nodes = entry.getValue();
							_nodes.add(node);
						}
					}
				}
			}
			Map<AgentNode, Set<AgentNode>> tempMap = new HashMap<AgentNode, Set<AgentNode>>();
			for (Map.Entry<String, List<AgentNode>> entry : nodeMap.entrySet()) {
				Set<AgentNode> nodeSet = new HashSet<AgentNode>();
				for (AgentNode node : entry.getValue()) {
					if (node.getAgentClass().equals("1")) {
						if (!tempMap.containsKey(node)) {
							tempMap.put(node, nodeSet);
						} else {
							nodeSet = tempMap.get(node);
						}
					} else {
						nodeSet.add(node);
					}
				}
			}
			for (Map.Entry<AgentNode, Set<AgentNode>> entry : tempMap.entrySet()) {
				AgentNode _1leveNode = entry.getKey();
				applyProductList = readMoneyBarDao.qryMoneyBarApplyProductList(_1leveNode.getProductId());
				for (ApplyProduct applyProduct : applyProductList) {
					ApplyProductDTO ApplyProductDto = new ApplyProductDTO();
					Map<String, String> fieldValue = BeanRefUtil.getFieldValueMap(applyProduct);
					BeanRefUtil.setFieldValue(ApplyProductDto, fieldValue);
					Agent agent = new Agent();
					agent.setUserId(_1leveNode.getUserId());
					agent.setLoginName(_1leveNode.getLoginName());
					ApplyProductDto.setProduct(applyProduct.getProduct());
					ApplyProductDto.setApplyUser(applyProduct.getApplyUser());
					ApplyProductDto.setAgent(agent);
					applyProductdtoList.add(ApplyProductDto);
				}
				Set<AgentNode> _2leveNodeSet = entry.getValue();
				for (AgentNode _2leveNode : _2leveNodeSet) {
					applyProductList = readMoneyBarDao.qryMoneyBarApplyProductList2(_2leveNode.getProductId());
					for (ApplyProduct applyProduct : applyProductList) {
						ApplyProductDTO ApplyProductDto = new ApplyProductDTO();
						Map<String, String> fieldValue = BeanRefUtil.getFieldValueMap(applyProduct);
						BeanRefUtil.setFieldValue(ApplyProductDto, fieldValue);
						Agent agent = new Agent();
						agent.setUserId(_2leveNode.getUserId());
						agent.setLoginName(_2leveNode.getLoginName());
						ApplyProductDto.setProduct(applyProduct.getProduct());
						ApplyProductDto.setApplyUser(applyProduct.getApplyUser());
						ApplyProductDto.setAgent(agent);
						applyProductdtoList.add(ApplyProductDto);
					}
				}

			}
		} catch (DaoException e) {
			throw new ServiceException(e.getCause());
		}
		retMap.put("applyProductList", applyProductdtoList);
		return retMap;
	}

	@Override
	@Transactional
	public int addBarFavorite(Map<String, Object> param) throws ServiceException {
		try {
			int count = readMoneyBarDao.qryFavoriteMoneyBarCnt(param);
			if (count > 0) {
				return 2;
			} else {
				param.put("memberCnt", 1);
				writeMoneyBarDao.update(param);
				return writeMoneyBarDao.insertBarFavorite(param);	
			}
		} catch (DaoException e) {
			throw new ServiceException(e.getCause());
		}
	}
	
	@Override
	public Map<String, Object> qryProductAgentList(Map<String, Object> qryParam) throws ServiceException {
		Map<String, Object> retMap = new HashMap<String, Object>();
		Map<String, List<AgentNode>> nodeMap = new HashMap<String, List<AgentNode>>();
		List<AgentNode> nodes = new ArrayList<AgentNode>();
		List<AgentNode> retNodeList = new ArrayList<AgentNode>();
		try {
			nodes = readMoneyBarDao.qryMoneyBarAgentList(qryParam);
			for (AgentNode node : nodes) {
				if (node.getAgentClass().equals("1")) {
					List<AgentNode> _nodes = new ArrayList<AgentNode>();
					_nodes.add(node);
					nodeMap.put(node.getUserId() + "-" + node.getParentAgentId() + "-" + node.getAgentClass() + "-"
							+ node.getAgentProductId() + "-" + node.getOriginalProductId(), _nodes);
				} else {
					for (Map.Entry<String, List<AgentNode>> entry : nodeMap.entrySet()) {
						String[] splitKey = entry.getKey().split("-");
						if (splitKey[0].equals(String.valueOf(node.getParentAgentId()))
								&& splitKey[splitKey.length - 1].equals(String.valueOf(node.getOriginalProductId()))) {
							List<AgentNode> _nodes = entry.getValue();
							_nodes.add(node);
						}
					}
				}
			}
			
			Map<AgentNode, Set<AgentNode>> resultMap = new HashMap<AgentNode, Set<AgentNode>>();
			for (Map.Entry<String, List<AgentNode>> entry : nodeMap.entrySet()) {
				Set<AgentNode> nodeSet = new HashSet<AgentNode>();
				for (AgentNode node : entry.getValue()) {
					AgentNode _1leveNode = new AgentNode(node.getUserId(), node.getProfile(), node.getLoginName(),
							node.getOrderCount(), node.getAgentClass(), node.getOrgAuthFlag(), node.getParentAgentId(),
							node.getState(), null, null, null, null, null);
					if (_1leveNode.getAgentClass().equals("1")) {
						if (!resultMap.containsKey(_1leveNode)) {
							resultMap.put(_1leveNode, nodeSet);
						} else {
							nodeSet = resultMap.get(_1leveNode);
						}
					} else {
						nodeSet.add(_1leveNode);
					}
				}
			}

			for (Map.Entry<AgentNode, Set<AgentNode>> entry : resultMap.entrySet()) {
				AgentNode node = entry.getKey();
				List<AgentNode> children = new ArrayList<AgentNode>(entry.getValue());
				node.setChildren(children);
				retNodeList.add(node);
			}
		} catch (Exception e) {
			throw new ServiceException(e.getCause());
		}
		retMap.put("nodeList", retNodeList);
		return retMap;
	}

	@Override
	public Map<String, Object> qryProduct1LevelAgentList(Map<String, Object> qryParam) throws ServiceException {
		Map<String, Object> retMap = new HashMap<String, Object>();
		Map<String, List<AgentNode>> nodeMap = new HashMap<String, List<AgentNode>>();
		List<AgentNode> nodes = new ArrayList<AgentNode>();
		List<AgentNode> retNodeList = new ArrayList<AgentNode>();
		try {
			nodes = readMoneyBarDao.qryMoneyBarAgentList(qryParam);
			for (AgentNode node : nodes) {
				if (node.getAgentClass().equals("1")) {
					List<AgentNode> _nodes = new ArrayList<AgentNode>();
					_nodes.add(node);
					nodeMap.put(node.getUserId() + "-" + node.getParentAgentId() + "-" + node.getAgentClass() + "-"
							+ node.getAgentProductId() + "-" + node.getOriginalProductId(), _nodes);
				} else {
					for (Map.Entry<String, List<AgentNode>> entry : nodeMap.entrySet()) {
						String[] splitKey = entry.getKey().split("-");
						if (splitKey[0].equals(String.valueOf(node.getParentAgentId()))
								&& splitKey[splitKey.length - 1].equals(String.valueOf(node.getOriginalProductId()))) {
							List<AgentNode> _nodes = entry.getValue();
							_nodes.add(node);
						}
					}
				}
			}

			Map<AgentNode, Set<AgentNode>> resultMap = new HashMap<AgentNode, Set<AgentNode>>();
			for (Map.Entry<String, List<AgentNode>> entry : nodeMap.entrySet()) {
				Set<AgentNode> nodeSet = new HashSet<AgentNode>();
				for (AgentNode node : entry.getValue()) {
					AgentNode _1leveNode = new AgentNode(node.getUserId(), node.getProfile(), node.getLoginName(),
							node.getOrderCount(), node.getAgentClass(), node.getOrgAuthFlag(), node.getParentAgentId(),
							node.getState(), null, null, null, null,null);
					if (_1leveNode.getAgentClass().equals("1")) {
						if (!resultMap.containsKey(_1leveNode)) {
							resultMap.put(_1leveNode, nodeSet);
						} else {
							nodeSet = resultMap.get(_1leveNode);
						}
					} else {
						nodeSet.add(_1leveNode);
					}
				}
			}

			for (Map.Entry<AgentNode, Set<AgentNode>> entry : resultMap.entrySet()) {
				AgentNode node = entry.getKey();
//				List<AgentNode> children = new ArrayList<AgentNode>(entry.getValue());
//				node.setChildren(children);
				retNodeList.add(node);
			}
		} catch (DaoException e) {
			throw new ServiceException(e.getCause());
		}
		retMap.put("nodeList", retNodeList);
		return retMap;
	}

	@Override
	public Map<String, Object> qryAgentProductByIds(Map<String, Object> qryParam) throws ServiceException {
		Map<String, Object> retMap = new HashMap<String, Object>();
		Map<String, Object> agentProduct = null;
		try {
			agentProduct = readMoneyBarDao.qryAgentProductByIds(qryParam);
		} catch (DaoException e) {
			throw new ServiceException(e.getCause());
		}
		retMap.put("agentProduct", agentProduct);
		return retMap;
	}

	@Override
	public Map<String, Object> getMoneyBarStateById(Map<String, Object> qryParam) throws ServiceException {
		Map<String, Object> moneyBar = new HashMap<String, Object>();
		try {
			moneyBar = readMoneyBarDao.getMoneyBarStateById(qryParam);
		} catch (DaoException e) {
			throw new ServiceException(e.getCause());
		}
		return moneyBar;
	}
	
	@Override
	public int auditAgent(Map<String, Object> param) throws ServiceException {
		int count = 0;
		try {
			//删除提醒信息
			Map<String, Object> insertParam = new HashMap<String, Object>();
			insertParam.put("userId", param.get("auditUserId"));
			if ("1".equals(param.get("agentClass"))) {
				insertParam.put("type", "2");
			} else if ("2".equals(param.get("agentClass"))) {
				insertParam.put("type", "3");
			}
			insertParam.put("operatedUserId", param.get("userId"));
			writeReminderDao.delReminder(insertParam);
    		if ("2".equals(String.valueOf(param.get("state")))) {//拒绝
    			if ("1".equals(param.get("agentClass"))) {
        			//查询该代理人在该钱吧下是否还代理了其他产品
    				count = readAgentProductDao.qryOtherAgentProductCount2(param);
    			}
				if (count > 0) {//大于0表示已经有已审核通过的记录
					//Nothing
	    			//拒绝时，存在其他代理产品数据，不删除代理人数据
					param.put("state", "1");
					writeAgentDao.auditAgent(param);
				} else {
	    			//拒绝时，无其他代理产品，删除代理人数据
					count = writeAgentDao.delAgent(param);
				}
				if ("1".equals(param.get("agentClass"))) {
					//删除申请的代理产品记录
					writeProductDao.delAgentProduct(param);
				} else {
					List<Map<String, Object>> productList = readProductDao.qry1LevelAgentProductList(param);
					if (productList != null && productList.size() > 0) {
			    		for (Map<String, Object> p : productList) {
			    			param.put("agentProductId1", p.get("productId"));
							//删除申请的代理产品记录
							writeProductDao.del2LevelAgentProduct(param);
			    		}
			    	}
				}
    		} else {
    			count = writeAgentDao.auditAgent(param);
				if (count == 1) {
					//新增提醒信息
					insertParam = new HashMap<String, Object>();
					String type = "";
					List<Map<String, Object>> productList = null;
					if ("1".equals(param.get("agentClass"))) {
						type = "6";
						productList = readProductDao.qryUnAuditProductList(param);
					} else if ("2".equals(param.get("agentClass"))) {
						type = "6"; //红点提醒不区分一级、二级代理，将type=7 改成type=6， 2019/10/23
						//通过上级产品ID查询某个代理人所代理的产品ID
						productList = readProductDao.qry1LevelAgentProductList(param);
					}
			    	insertParam.put("userId", param.get("userId"));
			    	insertParam.put("type", type);
			    	if (productList != null && productList.size() > 0) {
			    		for (Map<String, Object> p : productList) {
			    			insertParam.put("productId", p.get("productId"));
			    			writeReminderDao.addReminder(insertParam);
			    		}
			    	}
			    	insertParam.put("platform", param.get("platform"));
			    	if ("1".equals(param.get("agentClass"))) {
				    	//更新代理产品状态
						writeProductDao.auditAgentProduct(param);
			    	} else {
				    	//更新代理产品状态
						writeProductDao.audit2LevelAgentProduct(param);
			    	}
    		    	Runnable runable = new AsyncThread(insertParam);
    		    	runable.run();
				}
    		}
		} catch (DaoException e) {
			throw new ServiceException(e.getCause());
		}
		return count;
	}
	
	/**
	 * 消息推送
	 */
	private void pushMessage(Map<String, Object> param) throws ServiceException {
		Map<String, Object> pushInfo = null;
		Map<String, String> map_jp = Maps.newHashMap();
		try {
			pushInfo = loginLogDao.qryPushIdByUserId(param);
			if (pushInfo == null || pushInfo.isEmpty() || pushInfo.get("pushId") == null || "".equals(pushInfo.get("pushId"))) {
				return;
			}
            String pushTitle = "【微介】代理人审核完成提醒";
            String pushContent = "您有新的代理人申请已受理，请注意查收";
            // 推送
            if ("Android".equals(param.get("platform"))) {
            	// jpush
                String deviceAndro = pushInfo.get("pushId").toString();
                //push消息
//                JPushUtils.pushAndroidMessageByRegistrationID(pushTitle, pushContent, deviceAndro);
                JPushUtils.pushAndroidNotificationByRegistrationID(pushTitle, pushContent, new HashMap(),deviceAndro);
            } else {
            	String[] deviceIos = param.get("IOS").toString().split(",");
            	JPushUtils.pushIosNotificationByRegistrationID(pushContent, map_jp, deviceIos);
            }
            logger.info("消息推送成功");
		}
		catch (DaoException e) {
			logger.info("消息推送失败");
			throw new ServiceException(e.getCause());
		}
	}

	@Override
	public List<Map<String, Object>> qryHomeMoneyBarList()throws ServiceException {
		List<Map<String, Object>> moneyBarList = null;
		try {
			moneyBarList = readMoneyBarDao.qryHomeMoneyBarList();
		} catch (DaoException e) {
			throw new ServiceException(e.getCause());
		}
		return moneyBarList;
	}
	
	public class AsyncThread implements Runnable {
		private Map<String, Object> param;

		AsyncThread(Map<String, Object> param) {
			this.param = param;
		}
		@Override
		public void run() {
			try {
				pushMessage(param);
			} catch (ServiceException e) {
				e.printStackTrace();
			}
		}
	}
}
